package com.example.likegifmarker.Utils;

import android.content.Context;
import android.net.Uri;
import android.widget.Toast;

import com.tencent.mmkv.MMKV;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class CacheUtil {
    public static String getIndexVideoPath() {
        return MMKV.defaultMMKV().getString("indexVideo", "");
    }

    public static void setIndexVideoPath(String path) {
        MMKV.defaultMMKV().putString("indexVideo", path);
    }

    public static File copyFileToPath(Context context, Uri uri, String path) {
        if (!new File(context.getCacheDir().getPath() + "/index").exists()) {
          if ( new File(context.getCacheDir().getPath() + "/index").mkdirs()){
              Toast.makeText(context, "创建目录失败，请检查存储权限", Toast.LENGTH_SHORT).show();
              return null;
          }
        }
        InputStream inputStream = null;
        File file = new File(path);
        if (file.exists()) {
            file.delete();
        }
        File targetFile = null;
        if (uri.getAuthority() != null) {
            try {
                inputStream = context.getContentResolver().openInputStream(uri);
                if (inputStream != null) {
                    int read;
                    byte[] buffer = new byte[8 * 1024];
                    //自己定义拷贝文件路径
                    targetFile = new File(path);
                    if (!targetFile.exists()){
                        targetFile.createNewFile();
                    }
                    OutputStream outputStream = new FileOutputStream(targetFile);
                    while ((read = inputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, read);
                    }
                    outputStream.flush();
                    try {
                        outputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    return targetFile;
                }

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (inputStream != null) {
                        inputStream.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return null;

    }
}
